package util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * json 工具类，依赖fastjson
 *
 * @author wanglei
 * @date 2022/2/27
 * */
public class JSONUtil {


    /** 替换所有空格，留下一个 */
    final private static String REPLACE_BLANK_ENTER = "\\s{2,}|t|\r|\n";
    final private static Pattern REPLACE_P = Pattern.compile(REPLACE_BLANK_ENTER);

    /** 使用正则表达式删除字符串中的空格、回车、换行符、制表符 */
    public static String replaceAllBlank(String str){
        String dest = "";
        if(!StringUtil.isBlank(str)){
            Matcher m = REPLACE_P.matcher(str);
            dest = m.replaceAll(StringUtil.EMPTY);
        }
        return dest;
    }

    /** 去除字符串中的空格、回车、换行符、制表符 */
    public static String replaceBlank(String source){
        String ret = StringUtil.EMPTY;
        if(!StringUtil.isBlank(source)){
            ret = source.replaceAll(StringUtil.LF, StringUtil.EMPTY)
                    .replaceAll("\\S{2,}", StringUtil.EMPTY)
                    .replaceAll(StringUtil.TAB, StringUtil.EMPTY)
                    .replaceAll(StringUtil.CR, StringUtil.EMPTY);
        }
        return ret;
    }

    /** 美化json字符串对象 输出json字符串 */
    public static String prettyFormatObject(String source){
        JSONObject jsonObject = JSONObject.parseObject(source);
        return JSON.toJSONString(
                jsonObject,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat
        );
    }

    /** 美化json字符串数组 输出json字符串 */
    public static String prettyFormatArray(String source){
        JSONArray jsonArray = JSONArray.parseArray(source);
        return JSON.toJSONString(
                jsonArray,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat
        );
    }
}
